<template>
  <div :class="[classSystem, className]" :id="id"></div>
</template>

<script>
import { reactive, toRefs, onMounted, watch } from 'vue'
import { Toast } from 'vant'

export default {
  name: 'PubVideo',
  props: {
    id: {
      type: String,
      // default: 'video'
    },
    config: {
      type: Object,
      default: function () {
        return {}
      }
    },
    className: {
      type: String,
      default: 'pub-video'
    },
    info: {
      type: Object,
      default: function () {
        return {}
      }
    }
  },
  emits: ['feedback', 'faild'],
  setup(props, ctx) {
    const state = reactive({
      classSystem: '',
      ckplayer: null,
      config: {
        container: `#${props.id}`,
        volume: 0,
        plug: 'hls.js'
      },
      isShowFeedback: false
    })

    const initPlayer = () => {
      Object.assign(state.config, props.config)
      if (!props.id) {
        console.log('请指定容器id')
        ctx.emit('faild')
        return false
      }
      if (!state.config.video) {
        console.log('未传入视频链接')
        ctx.emit('faild')
        return false
      }
      if (state.config.hasAuth) {
        Toast(`无权限访问该视频\n请前往 ‘我的’ 充值开通会员`)
        ctx.emit('faild')
        return false
      }
      state.ckplayer = new window.ckplayer(state.config)
      // 反馈
      state.ckplayer.feedback(() => ctx.emit('feedback'))
      // 旋转
      // state.ckplayer.rotate(90)
      // 切换视频
      // state.ckplayer.vars('video', 'http://localhost:3000/zxcu.m3u8')
      state.ckplayer.loadedMetaData(() => console.log('视频数据加载成功'))
      console.log('创建ckplayer，挂载容器：' + state.config.container)
    }

    const play = () => {
      state.ckplayer.play()
    }
    const pause = () => {
      state.ckplayer.pause()
    }

    watch(props.config, () => {
      console.log('watch props.config changed')
      initPlayer()
    })

    onMounted(async () => {
      console.log('onMounted initPlayer')
      initPlayer()
      window.addEventListener('resize', function () {
        Toast('window.orientation: ' + window.orientation)
        if (window.orientation == 0 || window.orientation == 180) {
          // ipad/iphone横屏，andriod竖屏
          state.classSystem = ''
        }
        else if (window.orientation == 90 || window.orientation == -90) {
          // ipad/iphone竖屏，andriod横屏
          state.classSystem = 'video-full-screen'
        }
      })
    })

    return {
      ...toRefs(state),
      play,
      pause
    }
  }
}
</script>

<style lang="scss" scoped>
.pub-video {
  width: 100%;
  height: 40vh;
}
// 首页大视屏
.home-video {
  width: 100%;
  height: 100vh;
}
// 横屏自动全屏
.video-full-screen {
  width: 100%;
  height: 100vh;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 262;
}
</style>
